Passed
Push — master ( fe7b3f...22651e )
by Andrey
08:30
created

$(document).ready   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 51
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 61
nc 2
nop 1
dl 0
loc 51
c 2
b 0
f 0
cc 2
rs 8.2763

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
2
// ISOTOPE FILTER
3
jQuery(document).ready(function($){
4
5
  if ( $('.iso-box-wrapper').length > 0 ) { 
6
7
      var $container  = $('.iso-box-wrapper'), 
8
        $imgs     = $('.iso-box img');
9
10
      $container.imagesLoaded(function () {
11
12
        $container.isotope({
13
        layoutMode: 'fitRows',
14
        itemSelector: '.iso-box'
15
        });
16
17
        $imgs.load(function(){
18
          $container.isotope('reLayout');
19
        })
20
21
      });
22
23
      //filter items on button click
24
25
      $('.filter-wrapper li a').click(function(){
26
27
          var $this = $(this), filterValue = $this.attr('data-filter');
28
29
      $container.isotope({ 
30
        filter: filterValue,
31
        animationOptions: { 
32
            duration: 750, 
33
            easing: 'linear', 
34
            queue: false, 
35
        }                
36
      });             
37
38
      // don't proceed if already selected 
39
40
      if ( $this.hasClass('selected') ) { 
41
        return false; 
42
      }
43
44
      var filter_wrapper = $this.closest('.filter-wrapper');
45
      filter_wrapper.find('.selected').removeClass('selected');
46
      $this.addClass('selected');
47
48
        return false;
49
      }); 
50
51
  }
52
53
});
54
55
// jQuery to collapse the navbar on scroll //
56
$(window).scroll(function() {
57
    if ($(".navbar").offset().top > 50) {
58
        $(".navbar-fixed-top").addClass("top-nav-collapse");
59
    } else {
60
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
61
    }
62
});
63
64
/* HTML document is loaded. DOM is ready. 
65
-------------------------------------------*/
66
$(function(){
67
68
  // ------- WOW ANIMATED ------ //
69
  wow = new WOW(
0 ignored issues
show
Bug introduced by
The variable WOW seems to be never declared. If this is a global, consider adding a /** global: WOW */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable wow seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wow.
Loading history...
70
  {
71
    mobile: false
72
  });
73
  wow.init();
74
75
  // HIDE MOBILE MENU AFTER CLIKING ON A LINK
76
  $('.navbar-collapse a').click(function(){
77
        $(".navbar-collapse").collapse('hide');
78
    });
79
80
  // NIVO LIGHTBOX
81
  $('.iso-box-section a').nivoLightbox({
82
        effect: 'fadeScale',
83
    });
84
85
});
86
87
/**
88
 * Serialize object to string.
89
 *
90
 * @param   {object} obj    - Object incoming
91
 * @returns {string}        - Object as Get params string
92
 */
93
function serializeParams(obj) {
94
    return Object.keys(obj).reduce(function(a,k) {a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&');
95
}
96
97
/**
98
 * AJAX function.
99
 *
100
 * @param {string} url     - Request URL
101
 * @param {string} method  - Request type ('post' || 'get')
102
 * @param {object} params  - Object with params (for files { name: 'sasha' (sended to $_POST[]), files: { custom_filename: element.files[0] } (sended to $_FILES[]))
103
 * @param {object} options - Object with options. Available options:
104
 *     response_json{bool} - Type of response (JSON or not)
105
 *     func_waiting{func}  - Function while waiting
106
 *     func_callback{func} - Function on success result
107
 *     func_error{func}    - Function on error result
108
 *     func_progress{func} - Function on uploading progress
109
 */
110
function AJAX(url, method, params, options) {
111
    var xhr = null;
112
113
    try { // For: chrome, firefox, safari, opera, yandex, ...
114
        xhr = new XMLHttpRequest();
115
    } catch(e) {
116
        try { // For: IE6+
117
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
118
        } catch(e1) { // if JS not supported or disabled
119
            console.log("Browser Not supported!");
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
120
            return;
121
        }
122
    }
123
124
    xhr.onreadystatechange = function() {
125
126
        // ready states:
127
        // 0: uninitialized
128
        // 1: loading
129
        // 2: loaded
130
        // 3: interactive
131
        // 4: complete
132
133
        if (xhr.readyState == 4) { // when result is ready
134
135
            var response_text = xhr.responseText;
136
137
            if ('response_json' in options && options.response_json) {
138
                try {
139
                    response_text = JSON.parse(response_text);
140
                } catch (e) { }
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
141
            }
142
143
            if (xhr.status === 200) { // on success
144
                if ('func_callback' in options && typeof options.func_callback == 'function') {
145
                    var fc = options.func_callback;
146
                    fc(response_text);
147
                }
148
            } else { // on error
149
                console.log(xhr.status + ': ' + xhr.statusText);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
150
                if ('func_error' in options && typeof options.func_error == 'function') {
151
                    var fe = options.func_error;
152
                    fe(response_text, xhr);
153
                }
154
            }
155
        } else { // waiting for result
156
            if ('func_waiting' in options && typeof options.func_waiting == 'function') {
157
                var fw = options.func_waiting;
158
                fw();
159
            }
160
        }
161
    };
162
163
    var data = null;
0 ignored issues
show
Unused Code introduced by
The assignment to data seems to be never used. If you intend to free memory here, this is not necessary since the variable leaves the scope anyway.
Loading history...
164
165
    if (params.files) {
166
        method = 'POST';
167
168
        data = new FormData();
169
        for (var index_param in params) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
170
            if (typeof params[index_param] == 'object') {
171
                for (var index_file in params[index_param]) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
172
                    data.append(index_file, params[index_param][index_file]);
173
                }
174
            } else {
175
                data.append(index_param, params[index_param]);
176
            }
177
        }
178
179
        if ('func_progress' in options && typeof options.func_progress == 'function') {
180
            xhr.upload.onprogress = function(event) {
181
                // 'progress: ' + event.loaded + ' / ' + event.total;
182
                var fp = options.func_progress;
183
                fp(event);
184
            }
185
        }
186
    } else {
187
        data = serializeParams(params);
188
    }
189
190
    method = method.toUpperCase();
191
192
    if (method == 'GET' && data) {
193
        url += '?' + data;
194
    }
195
196
    xhr.open(method, url, true);
197
198
    if ( ! params.files) {
199
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
200
    }
201
202
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
203
    xhr.send(data);
204
}
205
206
/**
207
 * Add cross browser event to DOM element
208
 *
209
 * @param {object} element			- Element for adding event
210
 * @param {string} event_name   	- Event name
211
 * @param {function} event_handler	- Event handler
212
 */
213
function addEvent(element, event_name, event_handler) {
214
    if (event_name == 'ready') {
215
        if (document.addEventListener) {
216
            document.addEventListener("DOMContentLoaded", event_handler, false);
217
        } else if (document.attachEvent) {
218
            document.attachEvent("onreadystatechange", function() {
219
                if (document.readyState === "complete" ) {
220
                    event_handler();
221
                }
222
            });
223
        }
224
    } else {
225
        if (element.addEventListener) {
226
            element.addEventListener(event_name, event_handler, false);
227
        } else if (element.attachEvent) {
228
            element.attachEvent('on' + event_name, event_handler);
229
        }
230
    }
231
}
232
233
// FEEDBACK
234
235
var recaptcha_status = 'passive';
236
237
$(document).ready(function() {
238
    /**
239
     * Single upload file.
240
     */
241
    var feedbackBlock = $('#feedback');
242
    feedbackBlock.on("click", '[role="send"]', function(e) {
243
        e.preventDefault();
244
        if (recaptcha_status == 'passive' || recaptcha_status == 'unvalid') {
245
            var textAlert;
246
            switch (recaptcha_status) {
247
                case 'passive':
248
                    textAlert = window.need_captcha;
249
                    break;
250
                case 'unvalid':
251
                    textAlert = window.error_captcha;
252
                    break;
253
            }
254
            showAlert(feedbackBlock, textAlert, 'danger');
0 ignored issues
show
Bug introduced by
The variable textAlert seems to not be initialized for all possible execution paths. Are you sure showAlert handles undefined variables?
Loading history...
255
            return;
256
        }
257
        closeAlert(feedbackBlock);
258
259
        var url = '/ajax/feedback-ajax/send',
260
            nameBlock = feedbackBlock.find('[role="name"]'),
261
            emailBlock = feedbackBlock.find('[role="email"]'),
262
            subjectBlock = feedbackBlock.find('[role="subject"]'),
263
            messageBlock = feedbackBlock.find('[role="message"]'),
264
            params = {
265
                _csrf: window.yii.getCsrfToken(),
266
                name: nameBlock.val(),
267
                email: emailBlock.val(),
268
                subject: subjectBlock.val(),
269
                message: messageBlock.val(),
270
                short_language: window.short_language
271
            };
272
273
        AJAX(url, 'POST', params, {
274
            response_json: true,
275
            func_waiting: function () {
276
                showPreloader();
277
            },
278
            func_callback: function (resp) {
279
                hidePreloader();
280
                if (resp.meta.status == 'success') {
281
282
                    feedbackBlock.find('.form-group').each(function () {
283
                        if ($(this).hasClass('has-error')) {
284
                            $(this).removeClass('has-error');
285
                        }
286
                        $(this).find('.help-block').text('');
287
                        $(this).find('.form-control').val('');
288
                    });
289
290
                    showAlert(feedbackBlock, window.sent_message, 'success');
291
                    setTimeout(function () {
292
                        closeAlert(feedbackBlock);
293
                        grecaptcha_reset();
294
                        recaptcha_status = 'passive';
295
                    }, 3000);
296
297
                } else if (resp.meta.status == 'fail') {
298
                    var errors = resp.data.errors;
299
                    feedbackBlock.find('.form-group').each(function () {
300
                        var dataGroup = $(this).attr('data-group');
301
                        var help_block = $('#help_block_'+dataGroup);
302
                        if (dataGroup in errors) {
303
                            if (!$(this).hasClass('has-error')) {
304
                                $(this).addClass('has-error');
305
                            }
306
                            help_block.text(errors[dataGroup][0]);
307
                        } else {
308
                            if ($(this).hasClass('has-error')) {
309
                                $(this).removeClass('has-error');
310
                            }
311
                            help_block.text('');
312
                        }
313
                    });
314
                }
315
            },
316
            func_error: function (resp) {
317
                console.log(resp.message);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
318
            }
319
        });
320
    });
321
});
322
323
/**
324
 * @param {element} parentBlock
325
 * @param {string} textAlert
326
 * @param {string} status
327
 *      success
328
 *      info
329
 *      warning
330
 *      danger
331
 */
332
function showAlert(parentBlock, textAlert, status) {
333
    var possibleStatuses = [
334
        'success',
335
        'info',
336
        'warning',
337
        'danger'
338
    ];
339
    var alertBlock = parentBlock.find('[role="alert"]');
340
    if (alertBlock.hasClass('nodisplay')) {
341
        alertBlock.removeClass('nodisplay');
342
    }
343
    if (!alertBlock.hasClass('display')) {
344
        alertBlock.addClass('display');
345
    }
346
    for (var i = 0; i < possibleStatuses.length; i++) {
347
        if (status != possibleStatuses[i]) {
348
            if (alertBlock.hasClass('alert-'+possibleStatuses[i])) {
349
                alertBlock.removeClass('alert-'+possibleStatuses[i]);
350
            }
351
        } else {
352
            if (!alertBlock.hasClass('alert-'+status)) {
353
                alertBlock.addClass('alert-'+status);
354
            }
355
        }
356
    }
357
    alertBlock.text(textAlert);
358
}
359
360
/**
361
 * @param parentBlock
362
 */
363
function closeAlert(parentBlock) {
364
    var possibleStatuses = [
365
        'success',
366
        'info',
367
        'warning',
368
        'danger'
369
    ];
370
    var alertBlock = parentBlock.find('[role="alert"]');
371
    if (alertBlock.hasClass('display')) {
372
        alertBlock.removeClass('display');
373
    }
374
    if (!alertBlock.hasClass('nodisplay')) {
375
        alertBlock.addClass('nodisplay');
376
    }
377
    for (var i = 0; i < possibleStatuses.length; i++) {
378
        if (alertBlock.hasClass('alert-'+possibleStatuses[i])) {
379
            alertBlock.removeClass('alert-'+possibleStatuses[i]);
380
        }
381
    }
382
    alertBlock.text('');
383
}
384
385
var validateRecaptchaFeedback = function () {
386
    validateRecaptcha({
387
        func_waiting: function () {
388
            showPreloader();
389
        },
390
        func_callback_error: function () {
391
            hidePreloader();
392
            recaptcha_status = 'unvalid';
393
        },
394
        func_callback_success: function () {
395
            hidePreloader();
396
            recaptcha_status = 'valid';
397
            closeAlert($('#feedback'));
398
        }
399
    });
400
};
401
402
// CAPTCHA
403
404
function grecaptcha_reset() {
405
    grecaptcha.reset();
0 ignored issues
show
Bug introduced by
The variable grecaptcha seems to be never declared. If this is a global, consider adding a /** global: grecaptcha */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
406
}
407
408
function grecaptcha_execute() {
409
    grecaptcha.execute();
0 ignored issues
show
Bug introduced by
The variable grecaptcha seems to be never declared. If this is a global, consider adding a /** global: grecaptcha */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
410
}
411
412
/**
413
 * Validate recaptcha, using ajax request to the google recaptcha service.
414
 *
415
 * @param callbacks
416
 *     func_waiting{func}  - Function while waiting
417
 *     func_callback_success{func} - Function on success result with status 200
418
 *     func_callback_error{Func} - Function on error result with status 200
419
 */
420
function validateRecaptcha(callbacks) {
421
    var url = "/ajax/recaptcha-ajax/validate";
422
    var params = {
423
        _csrf: window.yii.getCsrfToken(),
424
        g_recaptcha_response: grecaptcha.getResponse()
0 ignored issues
show
Bug introduced by
The variable grecaptcha seems to be never declared. If this is a global, consider adding a /** global: grecaptcha */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
425
    };
426
    AJAX(url, 'POST', params, {
427
        response_json: true,
428
        func_waiting: function () {
429
            if ('func_waiting' in callbacks && typeof callbacks.func_waiting == 'function') {
430
                var fw = callbacks.func_waiting;
431
                fw();
432
            }
433
        },
434
        func_callback: function (resp) {
435
            if (resp.meta.status == 'success') {
436
                if ('func_callback_success' in callbacks && typeof callbacks.func_callback_success == 'function') {
437
                    var fcs = callbacks.func_callback_success;
438
                    fcs(resp);
439
                }
440
            } else if (resp.meta.status == 'fail') {
441
                if ('func_callback_error' in callbacks && typeof callbacks.func_callback_error == 'function') {
442
                    var fce = callbacks.func_callback_error;
443
                    fce(resp);
444
                }
445
                grecaptcha_reset();
446
            }
447
        },
448
        func_error: function (resp, xhr) {
0 ignored issues
show
Unused Code introduced by
The parameter xhr is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter resp is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
449
            grecaptcha_reset();
450
        }
451
    });
452
}
453